/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef IMAGE_KNIFE_C_KEKE_API_BASE_H
#define IMAGE_KNIFE_C_KEKE_API_BASE_H

#include "log.h"
#include <dlfcn.h>

namespace ImageKnifePro {
class ApiBase {
public:
    explicit ApiBase(const char *soName);
    ~ApiBase();
    static int GetApiVersion();
protected:
    template<typename FuncType, int apiMinVersion>
    FuncType GetApiTemplate(const char *funcName)
    {
        if (GetHandle() == nullptr) {
            return nullptr;
        }

        if (GetApiVersion() < apiMinVersion) {
            IMAGE_KNIFE_LOG(LOG_WARN, "Get Func Failed, %{public}s Require Minimum API %{public}d",
                            funcName, apiMinVersion);
            return nullptr;
        }

        static FuncType apiFunc = reinterpret_cast<FuncType>(dlsym(GetHandle(), funcName));
        if (apiFunc == nullptr) {
            IMAGE_KNIFE_LOG(LOG_ERROR, "get %{public}s from %{public}s failed", funcName, soName_);
        }

        return apiFunc;
    }
private:
    const char *soName_;
    void *handle_ = nullptr;

    void *GetHandle();
};

}

#endif //IMAGE_KNIFE_C_KEKE_API_BASE_H
